import logging
from datetime import datetime
import pytest
from pathlib import Path
from tools.ERP上传 import 订单上传

logger = logging.getLogger(__name__)
date = datetime.now().strftime('%Y-%m-%d')
date_start = datetime.now().strftime('%Y-%m-%d 00:00:00')
date_end = datetime.now().strftime('%Y-%m-%d %H:%M:%S')


@pytest.mark.flaky(reruns=3, reruns_delay=2, reruns_show_all=True)
def 聚水潭导出订单_test(page_param, login_聚水潭):
    logger.info('开始操作聚水潭导出订单')
    page = page_param
    page.wait(1)
    if page.s_eles('text=知道了'):
        page('text=知道了').click()
    page.get('https://ww.erp321.com/app/order/export/exportorder.aspx?_c=jst-epaas')
    # 等待待ERP处理出现并勾选
    page.wait.ele_displayed('#other_qs', timeout=180)
    page.wait(5)
    x_eles = page.eles('#pop_close')
    for x_ele in x_eles:
        x_ele.click(by_js=True)
    page('#other_qs').ele('待ERP处理').click(by_js=True)
    page('搜付款时间').click(by_js=True)
    page('#order_date_begin').input(date_start, clear=True, by_js=True)
    page('#order_date_end').input(date_end, clear=True, by_js=True)
    page('#shop_site_淘宝天猫').click(by_js=True)
    page('#shop_site_阿里巴巴').click(by_js=True)
    page('#shop_site_天猫供销').click(by_js=True)
    page('#shop_site_淘工厂').click(by_js=True)
    # 点击搜索
    page('.btn_search').click()
    page.wait(5)
    # 导出订单
    logger.info('开始导出订单')
    page.set.download_file_name('订单.xlsx')
    page('#Tool_New_Btn').click()
    page.wait(3)
    eles = page.eles('#confirm_confirm')
    for ele in eles:
        ele.click(by_js=True)
        page.wait(1)
    eles = page.eles('#msg_close')
    for ele in eles:
        ele.click(by_js=True)
        page.wait(1)
    page.wait(2)
    # 进入下载订单页面
    logger.info('进入下载订单页面')
    page.get('https://ww.erp321.com/app/common/export/export_log.aspx?_t=1655800135943&_h=800px&_float=true')
    page.wait(5)
    trs = page.eles('._jt_row _jt_rh')
    for tr in trs:
        导出类型 = tr.child(6).text
        if 导出类型 == '订单':
            logger.info('聚水潭导出进度开始加载')
            while True:
                if tr.child(7).text == '100%':
                    logger.info('聚水潭导出进度100%')
                    break
                page.wait(1)
            page.set.download_path(f'C:/审单订单/{date}')
            page.set.download_file_name('订单.xlsx')
            tr('.btn downLoad').click(by_js=True)
            logger.info('等待订单文件下载')
            page.wait.download_begin(timeout=60)
            page.wait.downloads_done(timeout=60)
            logger.info('订单文件下载成功')
            break
            # 删除导出记录
    for i in range(len(page.eles("下载完成"))):
        eles = page.eles("._jt_row _jt_rh")
        for ele in eles:
            if '下载完成' in ele.text:
                ele.ele(".btn del").click()
                page.wait(2)
                break
    logger.info(f'文件上传ERP')
    订单上传(f'C:/审单订单/{date}/订单.xlsx')

